package flc.ast.widget.time;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;

import com.blankj.utilcode.util.Utils;
import com.stark.appwidget.lib.AppWidgetViewManager;
import com.stark.appwidget.lib.BaseAppWidgetView;

import stark.common.basic.utils.BroadcastReceiverUtil;

public abstract class BaseTimeWidget extends BaseAppWidgetView {

    protected Handler mHandler;
    protected Runnable taskUpdate;

    public BaseTimeWidget(int appWidgetId) {
        super(appWidgetId);
        registerReceiver();
    }

    @Override
    public void update(Context context) {
        registerReceiver();
        initInUpdate(context);
        onUpdate(context);
        mHandler.removeCallbacks(taskUpdate);
        mHandler.postDelayed(taskUpdate, 1000);
    }

    protected abstract void onUpdate(Context context);

    private void initInUpdate(Context context) {
        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }
        if (taskUpdate == null) {
            taskUpdate = new Runnable() {
                @Override
                public void run() {
                    update(context);
                }
            };
        }
    }

    @Override
    public void destroy() {
        unregisterReceiver();
        if (mHandler != null) {
            mHandler.removeCallbacks(taskUpdate);
            mHandler = null;
        }
    }

    private BroadcastReceiver mReceiver;

    //注册广播
    private void registerReceiver() {
        if (mReceiver == null) {
            mReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    AppWidgetViewManager.getInstance().updateAppWidgetView2Db(BaseTimeWidget.this);
                    update(context);
                }
            };
            IntentFilter filter = new IntentFilter();
            BroadcastReceiverUtil.registerReceiver(mReceiver, filter);
        }
    }

    //销毁广播
    private void unregisterReceiver() {
        if (mReceiver != null) {
            BroadcastReceiverUtil.unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }
}
